package com.mxin.network.interceptor.encrypt;

import com.mxin.common.log.LogA;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class ResponseEncryptInterceptor implements Interceptor {

    private IDecryptListener iDecrypt;

    public ResponseEncryptInterceptor(IDecryptListener iDecrypt) {
        this.iDecrypt = iDecrypt;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null && iDecrypt.isNeedDecrypt(request, response)) {
                /*开始解密*/
                try {
                    BufferedSource source = responseBody.source();
                    source.request(Long.MAX_VALUE);
                    Buffer buffer = source.getBuffer();
                    Charset charset = Charset.forName("UTF-8");
                    MediaType contentType = responseBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(charset);
                    }
                    String bodyString = buffer.clone().readString(charset);

                    String responseData = iDecrypt.decryptData(bodyString);
                    LogA.d(responseData);
                    /*将解密后的明文返回*/
                    ResponseBody newResponseBody = ResponseBody.create(contentType, responseData.trim());
                    response = response.newBuilder().body(newResponseBody).build();
                } catch (Exception e) {
                    /*异常说明解密失败 信息被篡改 直接返回即可 */
                    LogA.e("解密异常====》"+ e.getMessage());
                    return response;
                }
            } else {
                LogA.i("响应体为空");
            }
        }
        return response;
    }

}
